import java.net.*;
import java.io.*;

public class PlayerThread implements Runnable {

	private final Socket socket;
	private BufferedReader in = null;
	private PrintWriter out = null;
	private PlayerThread[] players;
	private int maxPlayers;
	private boolean isConnected;
	int id;
	boolean myTurn;
	Table myTable;
	String line;

	PlayerThread(Socket socket, PlayerThread[] players) {

		this.socket = socket;

		try {
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream(), true);
		} catch (IOException e) {
			System.out.println("Failed to create input or output stream");
		}

		this.players = players;
		maxPlayers = players.length;

		isConnected = true;

	}

	public void run() {

		line = null;
		out.println("***Welcome Player " + id + "***");
		out.println("***Write Q to exit***");
		out.println("~ID "+id);

		while (isConnected) {
			try {
				line = in.readLine();
				out.println("***Got your message: "+line+"!***");
			} catch (IOException e) {
				out.println("***Input stream error!***");
			}
			if (line==null) System.out.println("Error");

			if (line.equals("Q")) {
				quit();
			} else {
				if (myTurn && line.startsWith("*")) {
					synchronized (myTable) {
						myTable.notify();
					}
					;
					myTurn = false;
					out.println("Action has been made");
				} else {
					synchronized (myTable) {
						// System.out.println(id+": "+line);
						for (int i = 0; i < maxPlayers; i++) {
							if ((players[i] != null) && players[i] != this)
								players[i].sendMessage("<Player " + id + "> "
										+ line);
						}
					}
				}
			}
			line = null;
		}
	};

	public void sendMessage(String message) {
		synchronized (myTable) {
			out.println(message);
		}

	}

	public void messageEveryone(String message) {
		synchronized (myTable) {
			for (int i = 0; i < maxPlayers; i++) {
				if ((players[i] != null) && players[i] != this)
					players[i].sendMessage(message);
			}
		}
	}

	public String getLine() {
		return line;
	}

	public void close() {
		try {
			in.close();
			out.close();
			socket.close();
		} catch (IOException e) {
			System.out.println("Error while closing streams");
		}

	}

	public void setTable(Table table) {
		myTable = table;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void yourTurn() {
		myTurn = true;
		// synchronized (players) {
		out.println("***Your turn***");
		out.println("~TURN");

		// };
	}

	public void quit() {
		synchronized (myTable) {
			out.println("***Bye!***");
			messageEveryone("***Player " + id + " left***");
			messageEveryone("~LEFT "+id);
			players[id] = null;
			if (myTurn) {

				myTable.notify();
				System.out.println("Next person!");
			}

			myTable.countPlayers();
			isConnected = false;
			this.close();
		}
	}

}
